<template>
  <view class="container">
    <FilterNavbar :searchList="searchList" v-model:queryParam="queryParam" @confirm="toList">
      <template #center>
        <view class="navbar-title"> 运营成本 </view>
      </template>
    </FilterNavbar>
    <view class="page-filter">
      <ve-search-bar placeholder="申请人/收款方/客户信息/支出单号" v-model="queryParam.mixCode" @search="searchBarSearch" />
      <ve-tabs :actived="0" :list="tabs" @change="tabsChange" style="background: #ffffff"></ve-tabs>
      <order-tabs-labels ref="orderTabsLabelsRef" v-model="checkedLabels" :list="currLabelList" @change="tabsLabelsChangeFn" />
      <orderSummary :summaryData="summaryData" />
    </view>
    <scroll-view
      scroll-y
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
      refresher-enabled
      :refresher-triggered="refreshStatus"
      :enable-back-to-top="true"
      @refresherrefresh="resetRefresh(true)"
      @scrolltolower="reachBottom"
    >
      <view class="record-list">
        <OrderItem v-for="record in dataSource" :key="record.id" :record="record" @loadData="loadData" />
        <!-- 加载结束列表为空时展示 -->
        <ve-empty v-if="dataSource?.length == 0 && loadStatus == 'nomore'"></ve-empty>
        <!-- 底部加载状态 -->
        <ve-load-more v-else :status="loadStatus" bgColor="#F7F7F9"></ve-load-more>
      </view>
    </scroll-view>
    <ve-bottom-box v-if="isStaff && (usePermission('svmsapp:operate-cost.createapply') || usePermission('svmsapp:operate-cost.createpay'))">
      <ve-button v-if="usePermission('svmsapp:operate-cost.createapply')" type="primary" @click="createApply" size="long">
        新增报销单
      </ve-button>
      <ve-button v-if="usePermission('svmsapp:operate-cost.createpay')" type="primary" @click="createPay" size="long">新增付款单</ve-button>
    </ve-bottom-box>
  </view>
</template>

<script setup>
  import { ref, onMounted, nextTick, computed, reactive } from 'vue'
  import { onLoad, onUnload } from '@dcloudio/uni-app'
  import FilterNavbar from '@/components/FilterNavbar'
  import orderTabsLabels from './components/orderTabsLabels.vue'
  import { usePageDict } from '@/hooks/useDict'
  import useList from '@/hooks/useList'
  import OrderItem from './components/orderItem.vue'
  import orderSummary from './components/orderSummary.vue'
  import { usePermission } from '@/hooks/usePermission'
  import { findUserInfo } from '@/api/common/index'
  import { getStatusCount, getCostCountApi, getListCount } from '@/api/cost/index'
  import { http } from '@/utils/http'

  const dict = usePageDict('costToListDict')

  const tabs = ref([
    { label: '全部', num: 0, value: null },
    { label: '待审批', num: 0, value: 2 },
    { label: '审批中', num: 0, value: 3 },
    { label: '已撤回', num: 0, value: 5 },
    { label: '已驳回', num: 0, value: 6 },
    { label: '审批完成', num: 0, value: 4 },
    { label: '无需审批', num: 0, value: 1 },
    { label: '已作废', num: 0, value: 7 },
  ])

  const searchList = computed(() => {
    return [
      {
        prop: 'businessCode',
        label: '业务单号',
        type: 'input',
      },
      {
        prop: 'workCode',
        label: '工单号',
        type: 'input',
      },
      {
        prop: 'amount',
        label: '支出单金额',
        type: 'input-number',
      },
      {
        prop: 'costType',
        label: '支出单类型',
        type: 'picker',
        attrs: {
          options: dict.costType,
        },
      },
      {
        prop: 'refCostTypeList',
        label: '关联单据类型',
        type: 'remote-select',
        attrs: {
          title: '选择关联单据类型',
          type: 'dict',
          multiple: true,
          outData: dict.refCostType,
        },
      },
      {
        prop: 'workType',
        label: '工单类型',
        type: 'picker',
        attrs: {
          options: dict.workType,
        },
      },
      {
        prop: 'businessType',
        label: '业务类型',
        type: 'picker',
        attrs: {
          options: dict.businessType,
        },
      },
      {
        prop: 'checkStaffId',
        label: '审批人',
        type: 'remote-select',
        attrs: {
          type: 'store_check_list',
        },
      },
      {
        prop: 'payStatusList',
        label: '付款状态',
        type: 'remote-select',
        attrs: {
          title: '选择付款状态',
          type: 'dict',
          multiple: true,
          outData: dict.payStatus,
        },
      },
      {
        prop: 'feeOrgIdList',
        label: '费用产生门店',
        type: 'remote-select',
        attrs: {
          type: 'org_listByStaff',
          multiple: true,
        },
      },
      {
        prop: 'feeItem',
        label: '支出费项',
        type: 'remote-select',
        attrs: {
          type: 'cost_fee',
        },
      },
      {
        prop: 'applyStaffId',
        label: '申请人',
        type: 'remote-select',
        attrs: {
          type: 'store_staff_list',
        },
      },
      {
        prop: ['applyTimeStart', 'applyTimeEnd'],
        label: '申请时间',
        type: 'daterange-picker',
      },
      {
        prop: ['payTimeStart', 'payTimeEnd'],
        label: '付款时间',
        type: 'daterange-picker',
      },
      {
        prop: ['costFeeCreateTimeBegin', 'costFeeCreateTimeEnd'],
        label: '费用发生日期',
        type: 'daterange-picker',
        attrs: {
          mode: 'date',
        },
      },
    ]
  })

  const queryParam = ref({})
  const routeQuery = ref()

  const { resetRefresh, reachBottom, loadData, scrollTop, loadStatus, refreshStatus, dataSource } = useList('/V5/cost/list', queryParam)

  const createApply = () => {
    uni.navigateTo({
      url: '/pages/operate-cost/apply-form/index?page=operateCost',
    })
  }
  const createPay = () => {
    uni.navigateTo({
      url: '/pages/operate-cost/pay-form/index?page=operateCost',
    })
  }
  // 选中标签
  const checkedLabels = ref([])
  // 标签
  const currLabelList = ref([
    { name: '待我处理', index: 0, value: 1, prop: 'waitMeProcessingCount', num: 0 },
    { name: '等待付款', index: 1, value: 2, prop: 'waitPayCount', num: 0 },
    { name: '我申请的', index: 2, value: 3, prop: 'meApplyCount', num: 0 },
    { name: '我已处理', index: 3, value: 4, prop: 'meProcessingCount', num: 0 },
    { name: '无财务打款凭证', index: 4, value: 5, prop: 'notPayFileCount', num: 0 },
    { name: '有财务打款凭证', index: 5, value: 6, prop: 'payFileCount', num: 0 },
    { name: '批量付款', index: 6, value: 7, prop: 'batchPayCount', num: 0 },
  ])
  // 多选标签
  const tabsLabelsChangeFn = (val) => {
    dataSource.value = []
    resetRefresh()
    // val是索引
    queryParam.value.labelList = val.map((i) => currLabelList.value.find((item) => item.index == i).value)
    loadData()
    getListCountFn()
  }

  const tabsChange = (e) => {
    dataSource.value = []
    queryParam.value.labelList = []
    checkedLabels.value = []
    resetRefresh()
    switch (e) {
      case 0:
        queryParam.value.checkStatus = undefined
        loadData()
        getTagCount()
        break
      case 1:
        queryParam.value.checkStatus = 2
        loadData()
        getTagCount()
        break
      case 2:
        queryParam.value.checkStatus = 3
        loadData()
        getTagCount()
        break
      case 3:
        queryParam.value.checkStatus = 5
        loadData()
        getTagCount()
        break
      case 4:
        queryParam.value.checkStatus = 6
        loadData()
        getTagCount()
        break
      case 5:
        queryParam.value.checkStatus = 4
        loadData()
        getTagCount()
        break
      case 6:
        queryParam.value.checkStatus = 1
        loadData()
        getTagCount()
        break
      case 7:
        queryParam.value.checkStatus = 7
        loadData()
        getTagCount()
        break
    }
    getListCountFn()
  }
  const searchBarSearch = () => {
    dataSource.value = []
    resetRefresh()
    getTabCount()
    getTagCount()
    getListCountFn()
  }

  const toList = (params) => {
    queryParam.value = {
      ...queryParam.value,
      ...params,
    }
    resetRefresh()
    getTabCount()
    getTagCount()
    getListCountFn()
  }
  // 获取统计数量
  const initData = {
    waitPayAmount: 0,
    checkAmount: 0,
    payAmount: 0,
  }
  const summaryData = reactive({ ...initData })
  const getListCountFn = async () => {
    try {
      let { result } = await getListCount(queryParam.value)
      Object.assign(summaryData, result ? result : { ...initData })
    } catch (error) {
      Object.assign(summaryData, { ...initData })
    }
  }
  // 获取状态栏tab数量
  const getTabCount = () => {
    let tabParam = JSON.parse(JSON.stringify(queryParam.value))
    delete tabParam.checkStatus
    delete tabParam.labelList
    getStatusCount(tabParam).then(({ result }) => {
      if (result) {
        tabs.value.forEach((item) => {
          let value = item.value
          if (value) {
            item.num = result?.find((i) => i.checkStatus == value)?.num || 0
          }
        })
      }
    })
  }
  // 获取标签数量
  const getTagCount = () => {
    let tagParam = JSON.parse(JSON.stringify(queryParam.value))
    delete tagParam.labelList
    getCostCountApi(tagParam).then(({ result }) => {
      if (result) {
        currLabelList.value.forEach((item) => {
          let prop = item.prop
          if (prop) {
            item.num = result[prop] || 0
          }
        })
      }
    })
  }
  const setQuickNavigation = () => {
    nextTick(() => {
      if (routeQuery.value.tag) {
        queryParam.value.labelList = []
        if (routeQuery.value.tag == 1) {
          checkedLabels.value = [0]
          queryParam.value.labelList = [1]
        }
        if (routeQuery.value.tag == 2) {
          checkedLabels.value = [1]
          queryParam.value.labelList = [2]
        }
      }
      if (routeQuery.value.code) {
        queryParam.value.mixCode = routeQuery.value.code
      }
      loadData()
    })
  }
  // 判断是否为员工还是admin，admin不支持新增报销单和付款单
  const isStaff = ref(true)
  // 获取员工登录信息
  const getUserInfoApi = () => {
    findUserInfo({}).then((res) => {
      if (res.code == 200) {
        const data = res.result
        isStaff.value = data && data.employeeId ? true : false
      }
    })
  }

  onMounted(() => {
    loadData()
    getTagCount()
    getTabCount()
    getListCountFn()
  })

  // 更新当前这一条数据
  const resetRefreshCurrentData = () => {
    // 操作的数据
    const record = uni.getStorageSync('hotUpdate_operate-cost')
    if (record) {
      // 获取当前数据
      http({
        method: 'POST',
        url: '/V5/cost/list',
        data: {
          pageNumber: 1,
          pageSize: 10,
          ...queryParam.value,
          // 用code查询到当前的这条数据
          code: record.code,
        },
      }).then((res) => {
        if (res.code == 200) {
          let { data, total } = res.result
          const index = dataSource.value.findIndex((item) => item.code == record.code)
          if (index == -1) return
          if (total > 0 && data.length > 0) {
            const newInfo = data[0]
            // 更新数据
            Object.assign(dataSource.value[index], newInfo)
          } else {
            // 删除数据
            dataSource.value.splice(index, 1)

            // 更新updateFlag
            updateHotUpdateFlag(true)
          }
        }
      })
    }
  }

  onLoad((option) => {
    getUserInfoApi()
    routeQuery.value = option
    if (routeQuery.value.tag || routeQuery.value.code) {
      setQuickNavigation()
    }
    uni.$on('refreshData', (force = false) => {
      if (force) {
        refreshData()
      } else {
        console.log('hot更新===hotUpdate_operate-cost')
        resetRefreshCurrentData()
      }
      getTagCount()
      getTabCount()
      getListCountFn()
    })
  })
  onUnload(() => {
    uni.$off('refreshData')
  })
</script>

<style lang="less" scoped>
  .container {
    height: 100vh;
  }
  .ve-search {
    padding-bottom: 10rpx;
  }
  .operate-line {
    width: 100%;
    height: 2rpx;
    background: #f7f8fa;
  }
  .record-list {
    padding: 24rpx;
  }
</style>
